package com.example.producer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * Created by crj on 2018/1/22.
 */
@Component
public class Sender {
    @Autowired
    private RabbitTemplate template;

    @PostConstruct
    public void setup() {
        //消息发送完成之后 则调用此方法 ack表示发送成功与否
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String s) {
                //ack 为 true 表示MQ表示已经发送成功
                if (!ack) {
                    return;
                }
                //TODO 发送成功之后的操作 这里只做打印
                log.info("mq 收到消息 id为" + correlationData.getId());
            }
        });
    }


    private Logger log = LoggerFactory.getLogger(Sender.class);

    public void send(String queue, String str) {
        log.info("send queue: " + queue + "   message:" + str);
        template.convertAndSend(queue, (Object) str, new CorrelationData(System.currentTimeMillis() + ""));
    }
}
